package com.union.config;

import org.apache.commons.configuration.ConfigurationException;
import org.apache.commons.configuration.PropertiesConfiguration;
import org.apache.commons.configuration.reloading.FileChangedReloadingStrategy;
import org.springframework.boot.ApplicationArguments;
import org.springframework.boot.ApplicationRunner;
import org.springframework.stereotype.Service;

@Service
public class Config implements ApplicationRunner {
	
	
	private static PropertiesConfiguration propConfig;
	private static final Config CONFIG = new Config();
	public static final String path = "static/amount.properties";
	
	@SuppressWarnings("static-access")
	@Override
	public void run(ApplicationArguments args) throws Exception {
		this.getInstance();
	}

	/**
	 * 自动保存
	 */
	private static final boolean autoSave = true;

	private Config() {
	}

	public static Config getInstance() {
		// 执行初始化
		init(path);
		return CONFIG;
	}

	/**
	 * 初始化
	 *
	 * @param propertiesFile
	 * @see
	 */
	private static void init(String propertiesFile) {
		try {
			propConfig = new PropertiesConfiguration(propertiesFile);
			// 自动重新加载
			propConfig.setReloadingStrategy(new FileChangedReloadingStrategy());
			// 自动保存
			propConfig.setAutoSave(autoSave);
		} catch (ConfigurationException e) {
			e.printStackTrace();
		}
	}

	/**
	 * 根据Key获得对应的value
	 *
	 * @param key
	 * @return
	 * @see
	 */
	public static Object getValue(String key) {
		return propConfig.getProperty(key);
	}

	/**
	 * 设置属性
	 *
	 * @param key
	 * @param value
	 * @throws ConfigurationException 
	 * @see
	 */
	public static void setProperty(String key, String value){
		propConfig.setProperty(key, value);
	}

}